<?php


namespace app\admin\controller\mall;


use app\common\business\Wechat;
use app\common\controller\AdminController;
use app\common\model\MallGroupsOrder;
use app\common\model\MallGroupsTeam;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Model;
/**
 * Class Groupsorder
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="拼团团长管理")
 */
class Groupsteam extends AdminController
{
    protected $relationSearch = true;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallGroupsTeam();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames3();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            if($list){
                $users='';
                foreach($list as $k=>$v){
                    $minfo =(new Wechat())->getOpenidById($v['openid']);
                    $list[$k]['nickName'] =$minfo['nickName'];
                    $orderinfo =(new MallGroupsOrder())->field('ordersn,teamnum,goods_name,goods_id,endtime')->where("id='".$v['order_id']."'")->find();
                    $list[$k]['ordersn'] =$orderinfo['ordersn'];
                    $list[$k]['goods_id'] =$orderinfo['goods_id'];
                    $list[$k]['goods_name'] =$orderinfo['goods_name'];
                    $list[$k]['teamnum'] =$orderinfo['teamnum'];
                    $list[$k]['endtime'] =$orderinfo['endtime']>0 ? date('Y-m-d H:i:s', $orderinfo['endtime']):'--';
                    $count =$this->model->where("parent_id='".$v['id']."'")->count();
                    $list[$k]['nownum'] =$count+1;

                    $usersa =$this->model->alias('t')->field('m.nickName,m.avatarUrl')->join('mall_member m','m.openid=t.openid')->where("t.parent_id='".$v['id']."'")->select()->toArray();
                    foreach($usersa as $kk=>$vv){
                        $users.=$vv['nickName'].'|';
                    }
                    if($users){
                        $users =substr($users,0,-1);
                    }
                    $list[$k]['users'] =$users;
                    $users='';
                }
            }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

}